import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('../views/frame/Layout.vue'),
      children:[{
        path:'/taskList',
        name:'taskList',
        component:()=>import('../views/business/task/TaskList.vue')
      }]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/Register.vue'),
    },
    {
      path: '/error',
      name: 'error',
      component: () => import('../views/Error.vue'),
    }
  ]
})
//全局路由守卫
router.beforeEach(async (to, from) => {
  const isAuthenticated = localStorage.getItem('isAuthenticated')
  if (
    // 检查用户是否已登录
    !isAuthenticated &&
    // ❗️ 避免无限重定向
    to.name !== 'login' && to.name !== 'register' && to.name !== 'error'
  ) {
    // 将用户重定向到登录页面
    return { name: 'login' }
  }
  if (!checkRouteExists(router.options.routes,to.path)){
    return {name:'error'}
  }
})

function checkRouteExists(routes:any, path:string) {
  for (const route of routes) {
    // 检查当前路由的路径
    if (route.path === path) {
      return true;
    }

    // 如果有子路由，则递归检查子路由
    if (route.children) {
      const childExists = checkRouteExists(route.children, path);
      if (childExists) {
        return true;
      }
    }
  }
  return false;
}
export default router
